package com.moon.ws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.moon.entity.Admin;
import com.moon.model.Msg;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WsHandler extends TextWebSocketHandler {
    private Map<String, WebSocketSession> clients = new ConcurrentHashMap<String, WebSocketSession>();

    public Map<String, WebSocketSession> getClients() {
        return clients;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //session.getId() 服务器给浏览器的代号  唯一标识
        System.out.println("连接建立:" + session.getId());
        clients.put(session.getId(), session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接断开:" + session.getId());
        clients.remove(session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//        System.out.println("接受消息:"+message.getPayload());
//        session.sendMessage(message);
        //获得登录者
        Admin admin = (Admin) session.getAttributes().get("admin");
        //组建消息
        Msg msg = JSONObject.parseObject(message.getPayload(), Msg.class);
        msg.setCreatetime(new Date());
        msg.setSender(admin.getAccount());
        TextMessage textMessage = new TextMessage(JSON.toJSONString(msg));
        //推送
        for (Map.Entry<String, WebSocketSession> c : clients.entrySet()) {
            Admin a = (Admin) c.getValue().getAttributes().get("admin");
            if (msg.getReceiver().equals("all")) {
                c.getValue().sendMessage(textMessage);
            } else {
                if (a.getGrpstr().equals(msg.getReceiver()) || a.getGrpstr().equals(msg.getSender())) {
                    c.getValue().sendMessage(textMessage);
                }
            }
        }
    }
}
